<template>
  <el-dialog class="shipping-method" title="批量修改发货仓库和运输方式" width="660" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div style="padding: 16px 0">
      <p class="text-[14px] text-[#3A4259] leading-[20px] mb-[16px]" v-if="rows.length > 1">
        <span>选择数据：</span>
        <span class="font-bold" style="color: #3487ff">{{ rows.length }}</span>
      </p>
      <p class="text-[14px] text-[#3A4259] leading-[20px] mb-[16px]" v-else>
        <span>系统订单号：</span>
        <span class="font-bold" style="color: #3487ff">{{ rows[0]?.order_sn }}</span>
      </p>

      <div>
        <el-form :inline="false" ref="formInstance" :model="formData" :rules="formRules">
          <el-form-item label="发货仓库" prop="delivery_warehouse_id">
            <SelectWarehouse v-model="formData.delivery_warehouse_id" style="width: 100%" @update:modelValue="deliveryChange" />
          </el-form-item>
          <el-form-item label="运输方式" prop="shipping_method_id" v-if="rows.length > 1">
            <!-- <SelectShippingMethod v-model="formData.shipping_method_id" style="width: 100%" /> -->

            <VXSelect
              :list="mapChannel"
              filterable
              style="width: 100%"
              :formatter="(data) => data.map((v) => ({ label: v.channel_name, value: v.id }))"
              collapse-tags
              placeholder="运输方式"
              v-model="formData.shipping_method_id"
              clearable
            />
          </el-form-item>

          <div v-else v-loading="shippingMethodLoading">
            <el-form-item label="运输方式" prop="shipping_method_id">
              <!-- :disabled="item.channel_id == formData.default_shipping_method_id" -->
              <el-select v-model="formData.shipping_method_id" clearable filterable style="width: 100%" @change="shippingChange">
                <el-option v-for="item in shippingMethodOpt" :key="item.id" :label="item.channel_name" :value="item.channel_id" />
              </el-select>

              <!-- <el-select v-model="currentRow.is_registered_text" disabled placeholder="是否挂号" style="width:100px;margin-left:10px;">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select> -->
            </el-form-item>

            <el-form-item label="当前运输方式">
              <template #label>
                当前运输方式
                <span style="margin-left: 20px">{{ formData.shipping_method }}</span>
              </template>
              <el-table
                ref="shippingTableRef"
                :data="shippingMethodOpt"
                highlight-current-row
                style="width: 100%"
                @current-change="handleCurrentChange"
                :default-sort="{ prop: '', order: 'ascending' }"
              >
                <el-table-column width="40">
                  <template #default="{ row }">
                    <!-- :disabled="row.channel_id == formData.default_shipping_method_id" -->
                    <el-radio class="label-none" v-model="formData.shipping_method_id" :label="row.channel_id" />
                  </template>
                </el-table-column>
                <el-table-column prop="channel_name" label="运输方式" />
                <el-table-column prop="is_registered" label="是否挂号" width="80">
                  <template #default="{ row }">
                    {{ row.is_registered ? "是" : "否" }}
                  </template>
                </el-table-column>
                <el-table-column prop="freight_cny" label="预估运费/RMB" sortable width="144" />
                <el-table-column prop="time_limit" label="预估时效/天" sortable width="130" />
              </el-table>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <el-button :disabled="loading" @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import SelectWarehouse from "@/components/Selects/SelectWarehouse/index.vue"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
import { apiGetChannel, feeTrialCalcFreight } from "@/api/public"
import { nextTick } from "vue"
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  rows: { type: Array, default: () => [] },
})
const currentRow = ref({})
const formInstance = ref()
const handleCurrentChange = (row) => {
  // formData.value.shipping_method_id = JSON.parse(JSON.stringify(row.channel_id))
  // currentRow.value = row
}
const shippingChange = (e) => {
  if (e) {
    currentRow.value = shippingMethodOpt.value.find((v) => v.channel_id == e)
  } else {
    currentRow.value = {}
  }
}
watch(
  () => props.modelValue,
  (val) => {
    if (val && props.rows.length == 1) {
      formData.value.delivery_warehouse_id = props.rows[0].logistics?.ship_warehouse_id || ""
      if (!formData.value.delivery_warehouse_id) return
      deliveryChange(formData.value.delivery_warehouse_id)
      formData.value.shipping_method = props.rows[0].logistics?.shipping_method

      formData.value.default_shipping_method_id = props.rows[0].logistics?.shipping_method_id
      // console.log(props.rows[0])
    }
  },
  { immediate: true }
)
// const open = ()=>{
//   // if (props.rows.length == 1) {
//   //   formData.value.delivery_warehouse_id = props.rows[0].logistics?.ship_warehouse_id || ""
//   //   deliveryChange(formData.value.delivery_warehouse_id)
//   //   formData.value.shipping_method = props.rows[0].logistics?.shipping_method
//   // }
//   // nextTick(()=>{
//   //   formInstance.value?.clearValidate()
//   // })
// }

const emit = defineEmits(["update:modelValue", "refresh", "submit"])

const formData = ref({
  delivery_warehouse_id: "",
  shipping_method_id: "",
})

const shippingTableRef = ref()
const loading = ref(false)
const shippingMethodLoading = ref(false)
const shippingMethodOpt = ref([])
// 获取发货仓库下的运输方式
const getTmsOverallOptions = (e) => {
  // apiGetChannel({ warehouse: [e] }).then(res => {
  //   shippingMethodOpt.value = res.data
  // })
  if (e) {
    shippingMethodLoading.value = true
    feeTrialCalcFreight({
      source_os: "oms",
      warehouse: [e],
      customer_order_no: props.rows[0]?.order_sn,
      destination_country: props.rows[0]?.recipient?.recipient_country,
    })
      .then((res) => {
        shippingMethodOpt.value = res.data
        nextTick(() => {
          shippingTableRef.value.sort("freight_cny", "ascending")
        })
      })
      .finally(() => {
        shippingMethodLoading.value = false
      })
  } else {
    shippingMethodOpt.value = []
  }
}
const mapChannel = ref([])
const deliveryChange = (e) => {
  if (!e) formData.value.delivery_warehouse_id = ""
  if (props.rows.length == 1) {
    formData.value.shipping_method_id = ""
    shippingMethodOpt.value = []
    getTmsOverallOptions(e)
  } else {
    apiGetChannel({ warehouse: [e], source_os: "oms" }).then((res) => {
      mapChannel.value = res.data?.filter((v) => v.status == 1)
      formData.value.shipping_method_id = ""
      if (!e) {
        mapChannel.value = []
      }
    })
  }
}

const formRules = reactive({
  delivery_warehouse_id: [{ required: true, message: "请选择发货仓库", trigger: "change" }],
  shipping_method_id: [{ required: true, message: "请选择运输方式", trigger: "change" }],
})

const handleSave = async () => {
  try {
    loading.value = true
    // const formValues = await form.value.submit()
    // const orderIds = props.rows?.map(n => n.id)
    const valid = await formInstance.value.validate()
    if (valid) {
      emit("submit", { input: formData.value })
      handleClose(true)
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = (refresh) => {
  shippingMethodOpt.value = []
  formData.value = {
    delivery_warehouse_id: "",
    shipping_method_id: "",
  }
  emit("update:modelValue", false)
  formInstance.value.resetFields()
  if (refresh) emit("refresh")
}
// defineExpose({ open })
</script>

<style lang="scss" scoped>
.shipping-method {
  .el-form-item {
    display: unset;
    :deep(.el-form-item__content) {
      margin-bottom: 16px;
    }
  }
}
:deep(.label-none) {
  .el-radio__label {
    display: none;
  }
}
</style>
